/**
 * @api post model.
 *
 * User: yunshengzhu
 * Date: 2020/12/8
 * Time: 下午2:56
 */
package model

import "pkg/cfg"

func CreateUserTransList(list []UserTransDb) error {
	return db.Create(&list).Error
}

func CreateUserTrans(obj UserTransDb) error {
	return db.Create(&obj).Error
}

func UpdateUserTransStatus(orderNumber string, status int64) error {
	return db.Exec(`update t_user_trans set status=? where order_number=?`, status, orderNumber).Error
}

func GetUserTransUserIdCount(userId int64, typ []int) (num int64, err error) {
	count := UserTransCountDb{}
	return count.Count, db.Select("sum(amount) as count").Where("user_id=? and typ in ?", userId, typ).Order("create_time desc").Take(&count).Error
}

func GetUserTransUserIdStatusAmount(userId int64, status int) (num int64, err error) {
	count := UserTransCountDb{}
	return count.Count, db.Select("sum(amount) as count").Where("user_id=? and status = ?", userId, status).Order("create_time desc").Take(&count).Error
}

func GetUserTransUserIdStatusCount(userId int64, typ []int, status int) (num int64, err error) {
	count := UserTransCountDb{}
	return count.Count, db.Select("sum(amount) as count").Where("user_id=? and typ in ? and status=?", userId, typ, status).Order("create_time desc").Take(&count).Error
}

func GetUserTransUserIdList(userId int64, typ []int) (list []UserTransDb, err error) {
	list = make([]UserTransDb, 0)
	return list, db.Where("user_id=? and typ in ?", userId, typ).Order("create_time desc").Find(&list).Error
}

func RemitAmount(orderNumber string) error {
	tx := db.Begin()
	userTrans := make([]UserTransDb, 0)
	err := tx.Where("order_number=?", orderNumber).Find(&userTrans).Error
	if err != nil {
		cfg.LogErr("err:", err)
		tx.Rollback()
		return err
	}

	for _, v := range userTrans {
		if v.Status == 2 {
			err = tx.Exec(`update t_user set amount=amount+? where user_id=?`, v.Amount, v.UserId).Error
			if err != nil {
				cfg.LogErr("err:", err)
				tx.Rollback()
				return err
			}

			err = tx.Exec(`update t_user_trans set status=1 where id=?`, v.Id).Error
			if err != nil {
				cfg.LogErr("err:", err)
				tx.Rollback()
				return err
			}
		}
	}
	tx.Commit()
	return nil
}
